/* eslint-disable no-console */
/* eslint-disable no-unused-vars */
"use strict";
import { app, protocol, BrowserWindow, ipcMain, dialog, Menu } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import { filters } from "./main/arduino";
import path from "path";
import fond from "./main/home";
import { autoUpdater } from "electron-updater";
import log from "electron-log";
import urllib from "urllib";
import yaml from "js-yaml";
autoUpdater.autoDownload = false;
const isDevelopment = process.env.NODE_ENV !== "production";
const title = `DouBao-北京哈工科教机器人科技有限公司`;
app.commandLine.appendSwitch("ignore-gpu-blacklist", "true");
app.commandLine.appendSwitch("enable-zero-copy", "true");
app.commandLine.appendSwitch("disable-software-rasterizer", "false");
app.commandLine.appendSwitch("enable-native-gpu-memory-buffers", "true");
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let contents;
let mainWindow;
let portWindow;
let splash;
let qzgx = false;

// Standard scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } }
]);
const load = process.env.WEBPACK_DEV_SERVER_URL || "app://./";
const icon = process.env.NODE_ENV === 'development'?path.join(__dirname, "./build/logo128.png"):path.join(__dirname, "./icon.ico")
// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", data => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
} else {
  const template = [
    {
      label: "View",
      submenu: [
        { role: "reload" },
        { role: "forcereload" },
        { role: "toggledevtools" },
        { type: "separator" },
        { role: "resetzoom" },
        { role: "zoomin" },
        { role: "zoomout" },
        { type: "separator" },
        { role: "togglefullscreen" }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  // Menu.setApplicationMenu(menu)
  Menu.setApplicationMenu(null);
}

// 检查是否初始化
function creatzip(file) {
  createProtocol("app");
  let i = fond();
  if (i) {
    createWindow(file);
  } else {
    mainWindow = new BrowserWindow({
      width: 1280,
      height: 800,
      //closable: false,
      title,
      icon,
      webPreferences: {
        nodeIntegrationInWorker: true,
        nodeIntegration: true
      }
    });
    mainWindow.loadURL(`${load}/zip.html`);
    mainWindow.on("closed", function () {
      mainWindow = null;
    });
  }
}

function closezip() {
  mainWindow.destroy();
  app.relaunch();
  app.exit(0);
}

function createWindow(file = "") {
  let sb3 = "";
  try {
    sb3 = path.extname(file);
  } catch (err) {
    console.log(err);
    file = "";
  }

  splash = new BrowserWindow({
    width: 400,
    height: 400,
    frame: false,
    icon,
    title
  });
  splash.loadURL(`${load}loading.html`);

  mainWindow = new BrowserWindow({
    width: 1100,
    height: 810,
    show: false,
    title,
    icon,
    webPreferences: {
      nodeIntegrationInWorker: true,
      nodeIntegration: true,
      additionalArguments: [file]
    }
  });


  if (sb3 !== ".xml") {
    mainWindow.loadURL(`${load}index.html`);
  }


  mainWindow.on("closed", function () {
    if (portWindow) {
      portWindow.destroy();
    }
    mainWindow = null;
  });

  mainWindow.on("maximize", function () {
    mainWindow.webContents.send("maximize", true);
  });

  mainWindow.once("ready-to-show", () => {
    mainWindow.show();
    splash.close();
  });
}

function portassistant() {
  if (portWindow) {
    portWindow.show();
  } else {
    portWindow = new BrowserWindow({
      width: 768,
      height: 500,
      minWidth: 768,
      minHeight: 500,
      resizable: false,
      title,
      icon,
      webPreferences: {
        nodeIntegrationInWorker: true,
        nodeIntegration: true
      }
    });
    portWindow.loadURL(`${load}port/index.html`);
    contents = portWindow.webContents;
  }

  portWindow.on("closed", function () {
    contents = null;
    portWindow = null;
  });
}

app.on("ready", () => {
  console.log(process.argv);
  let file = process.argv[1] || "";
  creatzip(file);
});

app.on("quit", () => {
  // 关闭时检测是否是强制更新
  quitAndInstall(qzgx);
});

ipcMain.on("asynchronous-message", function (event, arg) {
  dialog.showOpenDialog(
    {
      title: "open hello world",
      filters: [
        {
          name: "blockly",
          extensions: ["xml"]
        }
      ],
      properties: ["openFile"]
    },
    function (filePath) {
      event.reply("asynchronous-reply", filePath);
    }
  );
});

ipcMain.on("saveXml", async (event, arg) => {
  const { filePath } = await dialog.showSaveDialog(
    mainWindow,
    {
      title: "保存",
      defaultPath: path.join(__dirname, "./sample/"),
      filters: [
        {
          name: "Blockly",
          extensions: ["xml"]
        }
      ],
      securityScopedBookmarks: true
    }
  );
  if (filePath) {
    try {
      let sta = await filters(filePath, arg.text);
      event.reply("asynchronous-reply", [true, "保存成功"]);
    } catch (err) {
      event.reply("asynchronous-reply", [false, "保存失败"]);
    }
  }
});

ipcMain.on("open-file", async (event, _arg) => {
  console.log("open-file")
  const { filePaths = [], canceled } = await dialog.showOpenDialog(mainWindow,
    {
      title: "打开",
      defaultPath: path.join(__dirname, "./sample/"),
      filters: [
        {
          name: "Blockly",
          extensions: ["xml"]
        }
      ]
    }
  );
  console.log(filePaths[0])
  console.log(canceled)
  if (filePaths[0]) {
    event.reply("file-path", filePaths[0]);
  }
});

ipcMain.on("openPortWin", (event, arg) => {
  portassistant();
});

ipcMain.on("closeport-admin", (event, arg) => {
  closeport();
});

ipcMain.on("closezip", (event, arg) => {
  closezip();
});

function closeport() {
  if (contents) {
    contents.send("closeport", "whoooooooh!");
  }
}

// if (!isDevelopment) {
//   let x = await getcheckForUpdates()
// if (x) {
//   if (x.isDown) {
//     qzgx = true
//     let ok = await autoUpdater.checkForUpdates()
//     console.log(ok)
//     if (ok) {
//       autoUpdater.autoDownload = true;
//       autoUpdater.checkForUpdatesAndNotify()
//     }
//   } else {
//     dialog.showMessageBox({
//       type: 'info',
//       message: 'DouBao编程软件发现新版本',
//       buttons: ['更新', '稍后更新']
//     }, (response, checkboxChecked) => {
//       if (response) {
//         autoUpdater.autoDownload = true;
//         autoUpdater.checkForUpdatesAndNotify()
//       }
//     })
//   }
// }
// }

async function getcheckForUpdates() {
  let yml = "latest.yml";
  if (process.platform !== "win32") {
    yml = "latest-mac.yml";
  }
  try {
    const url = await urllib.request(
      `https://doubaobit.oss-cn-beijing.aliyuncs.com/scratch/${yml}`
    );
    const jsons = yaml.safeLoad(url.data.toString());
    const version = jsons.version;
    const isDown = jsons.isDown;
    const v = app.getVersion();
    const e =
      version.split(".")[0] * 100 +
      version.split(".")[1] * 10 +
      version.split(".")[2];
    const f = v.split(".")[0] * 100 + v.split(".")[1] * 10 + v.split(".")[2];
    if (f < e) {
      return {
        isDown
      };
    }
  } catch (err) {
    console.log(err);
  }
  return false;
}

ipcMain.on("autoUpdater", async (event, arg) => {
  if (arg == "检查更新") {
    autoUpdater.checkForUpdates();
  } else if (arg == "开始更新") {
    autoUpdater.downloadUpdate();
  } else if (arg == "开始安装") {
    qzgx = false;
    quitAndInstall(true);
  } else if (arg == "init") {
    const x = await getcheckForUpdates();
    if (x) {
      if (x.isDown) {
        qzgx = true;
      }
      autoUpdater.checkForUpdates();
    }
  }
});

function quitAndInstall(i) {
  if (i) autoUpdater.quitAndInstall();
}

autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = "info";
log.info("App starting...");

autoUpdater.on("checking-for-update", () => {
  log.info("Checking for update...");
});
autoUpdater.on("update-available", info => {
  log.info("Update available.");
  console.log(info);
  mainWindow.webContents.send("检查更新", { download: true, qzgx });
});
autoUpdater.on("update-not-available", info => {
  log.info("Update not available.");
  mainWindow.webContents.send("检查更新", { download: false });
});
autoUpdater.on("error", err => {
  log.info("Error in auto-updater. " + err);
  mainWindow.webContents.send("检查更新", { download: false });
});
autoUpdater.on("download-progress", progressObj => {
  let log_message = "Download speed: " + progressObj.bytesPerSecond;
  log_message = log_message + " - Downloaded " + progressObj.percent + "%";
  log_message =
    log_message +
    " (" +
    progressObj.transferred +
    "/" +
    progressObj.total +
    ")";
  log.info(log_message);
  mainWindow.setProgressBar(progressObj.percent / 100);
  mainWindow.webContents.send("开始更新", { percentage: progressObj.percent });
});

autoUpdater.on("update-downloaded", (event, releaseNotes, releaseName) => {
  mainWindow.webContents.send("开始更新", { percentage: 100, qzgx });
});
